﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.Core.ServiceImpl.Repositories.Interface;
using EzDesk.Core.Model;

namespace EzDesk.Core.ServiceImpl.Repositories
{
    public class FeedTemplateRepository : IFeedTemplateRepository, IRepository<FeedTemplate>
    {
        private EzDeskDataContext _db;

        public FeedTemplateRepository(EzDeskDataContext db)
        {
            _db = db;
        }

        public FeedTemplateRepository()
            : this(new EzDeskDataContext())
        { }

        #region IRepository<FeedTemplate> Members

        public void SaveChanges()
        {
            _db.SubmitChanges();
        }

        public Guid Add(FeedTemplate model, bool saveChanges = true)
        {
            var entity = model.ToEntity();
            _db.ez_FeedTemplates.InsertOnSubmit(entity);

            if (saveChanges)
            {
                SaveChanges();
            }

            return entity.TempleId;
        }

        public FeedTemplate GetById(Guid id)
        {
            FeedTemplate model = null;
            if (id != null)
            {
                model = _db.ez_FeedTemplates.Where(p => p.TempleId == id)
                    .SingleOrDefault()
                    .ToModel();
            }
            return model;
        }

        public IQueryable<FeedTemplate> GetAll()
        {
            return from template in _db.ez_FeedTemplates
                   select new FeedTemplate()
                   {
                       Id = template.TempleId,
                       TemplateName = template.TemplateName,
                       Title = template.Title,
                       Body = template.Body,
                       TemplateIconName = template.TemplateIcon,
                       DefaultType = template.DefaultType,
                   };                  
        }

        public void Delete(Guid id, bool saveChanges = true)
        {
            var entity = _db.ez_FeedTemplates.Where(p => p.TempleId == id)
                .SingleOrDefault();
            _db.ez_FeedTemplates.DeleteOnSubmit(entity);

            if (saveChanges)
            {
                SaveChanges();
            }
        }

        public void Update(FeedTemplate model, bool saveChanges = true)
        {
            var entity = _db.ez_FeedTemplates.FirstOrDefault(p => p.TempleId == model.Id);
            if (entity != null)
            {
                ModelConvert.CopyValueFeedTemplate(entity, model);
            }

            if (saveChanges)
            {
                SaveChanges();
            }
        }
        #endregion
    }
}
